<template>
  <div>
    <h3 class="title">
      <span>新增课程</span>
      <!-- <span v-if="formDis ===false && isEdit === false">新增课程</span>
      <span v-if="isEdit === true">编辑商品</span>
      <span v-if="formDis === true">查看详情</span> -->
    </h3>
    <el-form
      ref="prductForm"
      :disabled="formDis"
      :model="prductForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      style="margin-top: 20px;">
      <el-form-item :prop="formDis?'':'name'" label="课程名称">
        <el-col :span="23" >
          <el-input
            v-model="prductForm.name"
            placeholder="请输入课程名称, 限制20个字符"
            type="text"
            maxlength="20"
            show-word-limit
          />
        </el-col>
      </el-form-item>
      <el-form-item label="课程介绍" prop="introduction" class="add_tip">
        <div style="width:98%">
          <div v-if="formDis" class="tin_box" v-html="$xss(prductForm.tips)" />
          <tinymce v-else v-model="prductForm.introduction" :height="260" :disabled="tinymceDis" />
        </div>
      </el-form-item>
      <el-form-item :prop="formDis?'':'categoryId'" label="课程类别">
        <el-col :span="8" >
          <el-select v-model="prductForm.categoryId">
            <el-option v-for="(item,index) in getCategoryList" :key="index" :value="item.id" :label="item.categoryName"/>
          </el-select>
        </el-col>
      </el-form-item>
      <hr>
      <el-form-item :class="formDis?'':'add_tip'" label="上传封面图" prop="'cost'">
        <el-col :span="24" >
          <div style="width:320px" class="fl">
            <div class="thumbnail">
              <img v-show="prductForm.imgUrl" :src="prductForm.imgUrl" alt="">
            </div>
            <div v-if="!formDis" class="uploadBox">
              <vueCropper
                :img-list.sync="addForm.cover"
                :fixed-number="[16,8]"
                :limit="1"
                img-type="slt"
                class="upload-demo fl"
                @modalShowFn="getModalStatus" />
              <el-button v-show="prductForm.imgUrl" class="btn_clear fr" size="small" type="info" @click="clearPic()">清除</el-button>
              <!-- <p slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件</p> -->
            </div>
          </div>
        </el-col>
      </el-form-item>
      <hr>
      <el-form-item :class="formDis?'':'add_tip'" label="上传课程视频" prop="'cost'">
        <el-col :span="24" >
          <div style="width:340px" class="fl">
            <div class="thumbnail_video">
              <!-- <img v-show="prductForm.imgUrl" :src="prductForm.imgUrl" alt=""> -->
              <video
                v-if="prductForm.videoUrl"
                :poster="prductForm.imgUrl"
                :src="prductForm.videoUrl"
                class="avatar video-avatar"
                style="width: 320px;height:180px"
                controls="controls">
                您的浏览器不支持视频播放
              </video>
            </div>
            <div v-if="!formDis" class="uploadBox">
              <el-upload
                ref="videoUpload"
                :before-remove="beforeRemove"
                :before-upload="beforeAvatarUpload"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
                :action="actionUrl"
                :http-request="sliderRequest"
                :with-credentials= "false"
                multiple
                class="upload-demo fl">
                <el-button size="small" type="primary" plain>选择视频</el-button>
              </el-upload>
              <el-button v-show="prductForm.videoUrl" class="videoBtn_clear fr" size="small" type="info" @click="clearVideo()">清除</el-button>

              <el-progress v-if="progressFlag" :percentage="loadProgress"/>
              <br>
              <!-- <p slot="tip" class="el-upload__tip">只能上传mp4/ogg/flv/avi/wmv/rmvb/mov文件</p> -->
            </div>
            <!-- <div class="fl tipBox">
              <p slot="tip" class="el-upload__tip">只能上传mp4/ogg/flv/avi/wmv/rmvb/mov文件</p>
            </div> -->
          </div>
        </el-col>
      </el-form-item>
      <!-- {{ prductForm }} -->
      <el-form-item :class="formDis?'':'add_tip'" label="个人信息参数" prop="manageVariableParameters">
        <el-col :span="18" >
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"/>
          <el-checkbox-group v-model="prductForm.manageVariableParameters" @change="handleCheckedArgumentsChange">
            <el-checkbox v-for="(item, index) in personArgument" :key="index" :label="item.attribute" :value="item" style="width:130px;">{{ item.attribute }}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <el-form-item style="margin-top:40px">
        <!-- 编辑 -->
        <el-button v-preventReClick v-if="isEdit" type="primary" @click="submitForm('prductForm')">确定</el-button>
        <!-- 新增 -->
        <el-button v-preventReClick v-if="!isEdit && !formDis" type="primary" @click="submitForm('prductForm')">确定</el-button>
        <!-- 取消 -->
        <el-button v-preventReClick v-if="!formDis" :disabled="false" @click="$router.go(-1)">关闭</el-button>
      <!-- <el-button @click="resetForm('prductForm')">重置</el-button> -->
      </el-form-item>

    </el-form>
    <div class="bottomDiv">
      <el-button v-preventReClick v-if="formDis" @click="$router.go(-1)">关闭</el-button>
    </div>
  </div>
</template>

<script>
import config from '@/utils/config';
import { checkNotEmail, checkNum, checkStudentNum } from '@/utils/validateUtil';
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'

import vueCropper from '@/components/cropper'
import UploadImg from '@/components/cropper/uploadImage.vue'

import { getCategoryList, addCourseMessage, getCourseInfo } from '@/api/course'
import axios from 'axios'

import { getVariableParameters } from '@/api/registry'

export default {
  components: { Tinymce, vueCropper, UploadImg },
  // mixins: [mixin],
  data() {
    return {
      loadProgress: 0, // 动态显示进度条
      progressFlag: false, // 关闭进度条
      getCategoryList: [],
      fixedNumber: [16, 15],
      outputType: 'jpeg',
      addForm: {},
      uploadData: {
        key: '',
        token: ''
      },
      // ---------------------------------------
      categoryList: [], //  获取所有分类信息
      actionUrl: '',
      prductForm: {
        name: '', // 商品名称
        categoryId: '', // 商品类型
        introduction: '', // 课程介绍
        imgUrl: '', // 封面
        videoUrl: '', // 视频地址
        manageVariableParameters: []
      },
      list: [],
      rules: {
        // 1.征集活动名称
        name: [
          { required: true, message: '请填写课程名称', trigger: 'blur' }
        //   { pattern: /^[A-z0-9\u4e00-\u9fa5]*$/, message: '不能含有特殊字符', trigger: 'blur' }
        ],
        // 2.课程类别
        categoryId: [
          { required: true, message: '请选择课程类别', trigger: 'change' }
        ]
      },
      listQuery: {
        status: 1,
        pageNum: 0,
        pageSize: 1000
      },
      fileList: [],
      formDis: false,
      tinymceDis: false,
      isEdit: false,

      personArgument: [],
      allPersonArgument: [],
      checkAll: false,
      isIndeterminate: false
    }
  },
  created() {
    // 获取所有课程类型
    this.getCategoryListFn()
    // 查询所有可变参数
    this.getVariableParametersFn()
  },
  mounted() {
    const _self = this;
    console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      console.log(this.$route.query)
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      if (this.$route.query.isEdit) {
        this.specificationType = 'isEdit'
      }
      if (this.$route.query.isLook) {
        this.specificationType = 'formDis'
      }
      console.log(this.$route.query)
      // this.getActivityInfoFn(this.$route.query.data.id)
    }
    // this.uploadData.token = GetQiniuToken().uploadToken
  },
  methods: {
    // 全选按钮
    handleCheckAllChange(val) {
      this.prductForm.manageVariableParameters = val ? this.allPersonArgument : [];
      this.isIndeterminate = false;
    },
    handleCheckedArgumentsChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.allPersonArgument.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allPersonArgument.length;
    },
    // 查询所有可变参数
    getVariableParametersFn() {
      getVariableParameters().then(res => {
        console.log(res)
        if (res.code === '200') {
          this.personArgument = res.data
          res.data.forEach(item => {
            this.allPersonArgument.push(item.attribute)
          })
        }
      })
    },
    // 把个人信息可选参数数据格式转为后台格式
    filterManageVariableParameters(resList) {
      const list = Object.assign({}, resList)
      const resListArr = resList.manageVariableParameters
      console.log(resListArr, resListArr.length)
      console.log(this.personArgument, this.personArgument.length)
      const objarr = []
      for (let i = 0; i < this.personArgument.length; i++) {
        for (let j = 0; j < resListArr.length; j++) {
          console.log(this.personArgument[i].attribute, '====', resListArr[j])
          if (this.personArgument[i].attribute === resListArr[j]) {
            this.personArgument[i].variableParametersId = this.personArgument[i].id
            delete this.personArgument[i].id
            objarr.push(this.personArgument[i])
          }
        }
      }
      list.manageVariableParameters = objarr
      return list
      // console.log(objarr)
    },
    // 查询课程详情
    getCourseInfoFn(id) {
      getCourseInfo({ id }).then(res => {
        console.log('查询征集活动管理详情:', res)
        if (res.code === '200') {
          this.resList = res.data
          const obj = Object.assign([], this.resList.manageVariableParameters)
          const arr = []
          console.log(obj)
          obj.forEach(item => {
            arr.push(item.attribute)
          })
          this.resList.manageVariableParameters = arr
        }
      })
    },
    request(data) {
      console.log(data)
      if (this.isEdit) {
        // 编辑
      } else {
        // 新增
        addCourseMessage(data).then(response => {
          if (Number(response.code) === 200) {
            Message.success('新增成功')
            this.$router.go(-1);
          } else {
            Message.error(response.message + '-' + response.data)
          }
        });
      }
    },
    // 提交
    submitForm(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          if (!this.prductForm.introduction) {
            Message.error('请填写课程介绍')
            return
          }
          if (!this.prductForm.imgUrl) {
            Message.error('请填添加课程封面图')
            return
          }
          if (!this.prductForm.videoUrl) {
            Message.error('请填添加课程视频')
            return
          }
          const list = this.filterManageVariableParameters(this.prductForm)
          // console.log(list)
          this.request(list)
        }
      })
    },
    // 获取所有课程类别
    getCategoryListFn() {
      getCategoryList(this.listQuery).then(res => {
        if (res.code === '200') {
          this.getCategoryList = res.data.list
        } else {
          Message.error(res.message + '' + res.data)
        }
      })
      console.log()
    },
    // 删除缩略图
    clearPic() {
      this.$confirm('确定删除此图吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.prductForm.imgUrl = ''
        this.$refs.picUpload.clearFiles()
      }).catch(() => {})
    },
    // 删除video
    clearVideo() {
      this.$confirm('确定删除此视频吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.prductForm.videoUrl = ''
        this.$refs.videoUpload.clearFiles()
      }).catch(() => {})
    },
    getModalStatus(url) {
      console.log('上传七牛云返回的地址:', url)
      this.prductForm.imgUrl = url
    },
    sliderRequest(request) {
      const { action, data, filename, file } = request;
      // 新建formDate对象
      const formData = new FormData();
      for (const key in data) {
        formData.append(key, data[key]);
      }
      const fileType = file.type.split('/')[1]
      const keyname = `${new Date().getTime()}${Math.random().toString(36).slice(2)}.${fileType}`
      const token = GetQiniuToken().uploadToken
      formData.append('file', file);
      formData.append('key', keyname);
      formData.append('token', token);
      axios({
        headers: {
          contentType: 'multipart/form-data' // 需要指定上传的方式
        },
        url: 'https://up-z1.qiniup.com',
        method: 'post',
        data: formData,
        onUploadProgress: progressEvent => {
          this.progressFlag = true; // 显示进度条
          const complete = (progressEvent.loaded / progressEvent.total * 100 | 0)
          // console.log(complete)
          this.loadProgress = complete
        },
        timeout: 200000 // 防止文件过大超时
      }).then(res => {
        console.log('视频上传返回值::', res)
        if (res.status === 200) {
          Message.success('视频上传成功')
          this.progressFlag = false;
          this.prductForm.videoUrl = 'http://ht.ma3u.com/' + res.data.key
          console.log('http://ht.ma3u.com/' + res.data.key)
          request.onSuccess()
        } else {
          Message.error(res.message || '网络错误...');
        }
        this.showCropper = false
      }).catch(err => {
        // loading.close();
        console.log(err);
      });
    },
    beforeRemove(file, fileList) {
      console.log('file:::', file)
      console.log('fileList:::', fileList)
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`).then(() => {
          // let index = fileList
          console.log()
        })
      }
    },
    beforeAvatarUpload(file) {
      // const isLt200M = file.size / 1024 / 1024 < 200;

      // console.log(file.size / 1024 / 1024)
      console.log('文件格式:', file.type)
      //   if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov', 'video/quicktime'].indexOf(file.type) === -1) {
      //     this.$message.error('请上传支持的数据格式（mp4，flv，avi，wmv，rmvb，mov）');
      //     return false;
      //   }
      if (file.type.indexOf('video/') === -1) {
        this.$message.error('请上传视频格式文件');
        return false;
      }
    //   if (!isLt200M) {
    //     this.$message.error('图片大小不能超过 200MB!');
    //     return false;
    //   }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }

  }
}
</script>

<style lang="scss" scoped>
    body {
        overflow: visible !important;
    }
    .fl{
        float: left;
    }
    .fr {
        float: right
    }
    hr{
        border: none;
        border-top: 1px solid #ddd;
        margin: 30px 0;
    }

    // ------------------

    .el-checkbox+.el-checkbox{
        margin-left:0
    }
    .el-checkbox{
        margin-right:25px;
    }

    .tin_box {
        border: 1px ssolid #ddd;
        padding: 0 10px 0 10px;
        color:#666;
    }
    .title{
        margin: 30px;
        color:#333;

    }
    .el-table__header tr,
    .el-table__header th {
        padding: 0;
        height: 30px !important;
    }
    .el-table__body tr,
    .el-table__body td {
        padding: 0 !important;
        height: 30px !important;
    }
    .el-table td, .el-table th {
        padding: 0 !important;
    }
    .tipBox{
        margin-top: 50px;
        margin-left: 10px;
    }
    // .thumbnail{
    //     width: 302px;
    //     height: 151px;
    //     border: 1px solid #eee;
    //     border-radius: 5px;
    //     display: flex;
    //     // flex-item-align: center;
    // }
    .thumbnail_video, .thumbnail{
        padding: 10px;
        width: 340px;
        height: 200px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
    }

    .thumbnail img{
        width: 100% ;
    }
    .uploadBox{
        width: 100%;
        position: relative;
    }
     .btn_clear, .videoBtn_clear{
        position: absolute;
        bottom: -38px;
        right: 0;
        padding: 10px 30px;
    }
    .videoBtn_clear{
        bottom: 0px;
    }

    .productName{
        width:300px
    }

    .table{
        width: 100%;
        border-collapse: collapse;
        border-spacing: 0;
    }
    .table td{
        border: 1px solid #ddd;
        padding: 5px 10px;
    }

  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
  .el-upload-list, .el-form-item__content{
        display: none;
    }
    .el-upload-list{
        width: 50px;
        overflow: hidden;
    }

    .discontIpt{
        width:58%
    }

    .redBroder {
        border: 1px solid red;
        box-sizing: border-box;
        border-radius: 4px;
        transition: all .5s;
    }

    .lbImgCon{
        width:60px;
        height: 40px;
        border: 1px dashed #ddd;
        margin-top: 0px;
    }

    .lbImgBox{
        width:146px;
        overflow: hidden;
        vertical-align: top;
        padding-top: 4px;
    }
    .lbTitle{
        margin: 0 0 40px 4.5%;
        line-height: 50px;
        font-size: 14px;
    }
    .bottomDiv{
        padding:0 0 20px 11%;
    }

    .setting_ul{
        margin:0;
        padding:0;
        .title{
            width: 100%;
            height: 40px;
            line-height: 40px;
        }
    }
    .collapseItem{
        margin-left: 20px;
    }
</style>
